// index.ts
// 获取应用实例
// const app = getApp<IAppOption>()
import { requestPUT, requestGET } from '../../utils/service'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    sexArray: [
      '男', '女'
    ],
    userInfo: {} as any,
    endDate: new Date().toLocaleDateString(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let userInfo = wx.getStorageSync('userInfo')
    userInfo.sex = userInfo.gender == '男' ? 0 : 1
    this.setData({
      userInfo: userInfo
    })
  },
  // 输入姓名
  inputName(v: any) {
    console.log(v)
    let userInfo = this.data.userInfo
    userInfo.userName = v.detail.value
    this.setData({
      userInfo: userInfo
    })
  },
  // 性别选择
  pickerSex(v: any) {
    let userInfo = this.data.userInfo
    userInfo.sex = v.detail.value
    this.setData({
      userInfo: userInfo
    })
  },
  // 获取手机号
  getPhoneNumber(e: any) {
    console.log(e.detail.code)  // 动态令牌
    console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
    console.log(e.detail.errno)  // 错误码（失败时返回）
    if (e.detail.code) {
      requestGET("user/getPhoneByCode", { code: e.detail.code })
        .then((res: any) => {
          let userInfo = this.data.userInfo
          userInfo.phone = res.data.data
          this.setData({
            userInfo: userInfo
          })
        })
    }
  },
  // 生日选择
  pickerBirth(v: any) {
    console.log(v)
    let userInfo = this.data.userInfo
    userInfo.birthDay = v.detail.value
    this.setData({
      userInfo: userInfo
    })
  },
  // 头像选择
  chooseAvatar(e: any) {
    let userInfo = this.data.userInfo
    userInfo.avatar = e.detail.avatarUrl
    this.setData({
      userInfo: userInfo
    })
  },
  // 保存修改
  save() {
    const userInfo = this.data.userInfo
    const params = {
      "userName": userInfo.userName,
      "gender": userInfo.sex == 0 ? '男' : '女',
      "birthDay": userInfo.birthDay,
      "password": userInfo.password,
      "phone": userInfo.phone,
      "openId": userInfo.openId,
      "avatar": userInfo.avatar,
      // "smsAuthenticationCode": "string",
      // "wxAuthenticationCode": "string"
    }
    requestPUT("user/modify", params)
      .then((res: any) => {
        if (res.data.code == '200') {
          wx.setStorageSync('userInfo', userInfo)
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 2000,
            success: function () {
              setTimeout(function () {
                // 返回上层界面
                wx.navigateBack({
                  delta: 1
                })
              }, 2000)
            }
          })
        } else {
          wx.showToast({
            title: '修改失败',
            icon: 'error',
            duration: 2000
          })
        }
      })
  },
})
